<?php

/**
 * @desc PvLog 类，打印每次请求的详细日志
 * @date 2022-02-26
 * @author  zxiaofee
 * */

namespace App\Lib;

class PvLog {
    public static $startTime;
    public static $request;
    public static $response;
    public static $userId;
    public static $ip;
    public static $cookie;
    public static $requestTime;
    public static $ext;
    public static $ua;
    //写入日志 todo
    public static function write()
    {
        $pvData = [
            'time' => self::$requestTime,
            'request_time' => microtime(true) - PvLog::$startTime,
            'user_id' => self::$userId??0,
            'ip' => self::$ip,
            'cookie' => self::$cookie??'',
            'method' => self::$request->method(),
            'ua' => $_SERVER['HTTP_H5_USER_AGENT'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '',
            'path' => self::$request->path(),
            'url' => self::$request->fullUrl(),
            'request' => self::$request->all(),
            'response' => self::$response,
            'ext' => self::$ext??[],
        ];
        $dirName = 'PvLog';
        $dirPath = storage_path() . '/pvLogs';
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0777, true);
        }
        if (is_array($pvData)) {
            file_put_contents($dirPath . '/' . $dirName . '-' . date('YmdH') . '.log', json_encode($pvData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        } else {
            file_put_contents($dirPath . '/' . $dirName . '-' . date('YmdH') . '.log', json_encode($pvData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        }
    }
}

